package com.wfm.files.bio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class MappedByteBufferProcessor {
    public static void main(String[] args) {
        String inputFile = "input.txt"; // 文件 A 的路径
        String outputFile = "output.txt"; // 文件 B 的路径

        try (RandomAccessFile input = new RandomAccessFile(inputFile, "r");
             RandomAccessFile output = new RandomAccessFile(outputFile, "rw")) {

            FileChannel inputChannel = input.getChannel();
            FileChannel outputChannel = output.getChannel();

            long fileSize = inputChannel.size();
            MappedByteBuffer inputBuffer = inputChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileSize);
            MappedByteBuffer outputBuffer = outputChannel.map(FileChannel.MapMode.READ_WRITE, 0, fileSize);

            StringBuilder content = new StringBuilder();
            for (int i = 0; i < fileSize; i++) {
                char c = (char) inputBuffer.get();
                if (c == '\n' || c == '\r') {
                    content.append(c);
                } else {
                    content.append(c).append(",");
                }
            }

            // 处理每一行，去掉每行最后一个多余的逗号
            String[] lines = content.toString().split("\r?\n");
            StringBuilder processedContent = new StringBuilder();
            for (String line : lines) {
                if (line.endsWith(",")) {
                    processedContent.append(line.substring(0, line.length() - 1));
                } else {
                    processedContent.append(line);
                }
                processedContent.append("\n");
            }

            // 将处理后的内容写入输出缓冲区
            byte[] processedBytes = processedContent.toString().getBytes();
            outputBuffer.put(processedBytes);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}